﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using WcfServer.Classes.Server;
using WcfServer.Classes.Utility;

namespace Client.ViewModel
{
    class LoginViewModel :ViewModelBase
    {
        private string userName;
        public string UserName
        {
            set
            {
                if (userName != value)
                {
                    userName = value;
                    base.OnPropertyChanged("UserName");
                }
            }
            get
            {
                return userName;
            }
        }
        private string password;
        public string Password
        {
            set
            {
                if (password != value)
                {
                    password = value;
                    base.OnPropertyChanged("Password");
                }
            }
            get
            {
                return password;
            }
        }
        public ICommand loginCommand;
        public ICommand LoginCommand
        {
            get
            {
                if (loginCommand == null)
                {
                    loginCommand = new RelayCommand(param => this.LoginUser(), param => this.CanLogin);
                }
                return loginCommand;
            }
        }
        public void LoginUser()
        {
            var connection = new Client.ServerService.ServerServiceClient();
            LoginData ld = new LoginData()
            {
                UserID = UserName,
                UserIP = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork).ToString(),
                Password = EncryptionHandler.HashSHA256(Encoding.UTF8.GetBytes(Password)),
                Timestamp = DateTime.Now,
                UserSessionKey = KeyHandler.generateAESKey()
            };

            FileStream fs = new FileStream("server_public.xml", FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs);
            String xml = sr.ReadToEnd();

            byte[] response = connection.AuthenticateUser(ld.SendUsingServerPublic(xml));

            LoginResponse lr = new LoginResponse(response, ld.UserSessionKey);
            //TODO:Validate sign.
            //lr.Sign;
            foreach (var i in lr.Friends)
            {
                KeyHandler.savePublicXML(i.UserID, i.publicKey);
            }
            MainWindow.ClientServerSessionKey = ld.UserSessionKey;
            MainWindow.CurrentUserName = ld.UserID;
        }
        private bool CanLogin
        {
            get { return true; }
        }
    }
}
